﻿using System;
using System.Collections;
using System.IO;
using System.Xml;
using UnityEditor;

internal class EclipseProject
{
    private XmlDocument mManifestXml;
    private string mPackageName;
    private string mPlayerPackage;
    private string mProductName;
    private string mProjectPath;
    private string mStagingArea;
    private string mTargetApi;

    public EclipseProject(string playerPackage, string stagingArea, string projectPath, string packageName, string productName, int platformApiLevel)
    {
        this.mPlayerPackage = playerPackage;
        this.mStagingArea = stagingArea;
        this.mProjectPath = projectPath;
        this.mPackageName = packageName;
        this.mProductName = productName;
        this.mTargetApi = "target=android-" + platformApiLevel;
    }

    private void CopyDir(string dir)
    {
        FileUtil.CopyDirectoryRecursive(Path.Combine(this.mStagingArea, dir), Path.Combine(this.mProjectPath, dir), true);
    }

    private void CopyJavaFile(string activityBaseName, string activityType)
    {
        string unityActivityName = "UnityPlayer" + activityType;
        string activityName = activityBaseName + activityType;
        string str3 = Path.Combine(this.mProjectPath, "src");
        string str4 = this.mPackageName.Replace('.', '/');
        string path = Path.Combine(str3, str4);
        Directory.CreateDirectory(path);
        string str6 = Path.Combine(path, activityName + ".java");
        if (!File.Exists(str6))
        {
            string str7 = "com.unity3d.player";
            string str8 = unityActivityName + ".java";
            string str9 = str7.Replace('.', '/');
            string contents = File.ReadAllText(Path.Combine(Path.Combine(Path.Combine(this.mPlayerPackage, "src"), str9), str8)).Replace("package " + str7, "package " + this.mPackageName);
            if (unityActivityName != "UnityPlayerProxyActivity")
            {
                string str12 = "import com.unity3d.player.*;\n";
                int index = contents.IndexOf("import");
                contents = contents.Insert(index, str12);
            }
            contents = contents.Replace("class " + unityActivityName, "class " + activityName);
            if (unityActivityName == "UnityPlayerProxyActivity")
            {
                string oldValue = str7 + ".UnityPlayerActivity";
                string newValue = this.mPackageName + "." + activityBaseName + "Activity";
                contents = contents.Replace(oldValue, newValue);
                oldValue = str7 + ".UnityPlayerNativeActivity";
                newValue = this.mPackageName + "." + activityBaseName + "NativeActivity";
                contents = contents.Replace(oldValue, newValue);
            }
            File.WriteAllText(str6, contents);
            this.PatchActivityInManifest(activityName, unityActivityName);
        }
    }

    private void CopyJavaFiles(string activityBaseName)
    {
        this.CopyJavaFile(activityBaseName, "Activity");
        this.CopyJavaFile(activityBaseName, "NativeActivity");
        this.CopyJavaFile(activityBaseName, "ProxyActivity");
    }

    public void Create()
    {
        string from = Path.Combine(this.mPlayerPackage, "bin/classes.jar");
        string path = Path.Combine(this.mProjectPath, "classes.jar");
        if (!File.Exists(path))
        {
            FileUtil.CopyFileOrDirectory(from, path);
        }
        this.CopyDir("gen");
        this.CopyDir("res");
        this.CopyDir("libs");
        this.CopyDir("assets");
        string str4 = Path.Combine(Path.Combine(this.mStagingArea, "../../Assets"), "Plugins");
        string target = Path.Combine(this.mProjectPath, "Plugins");
        string[] pluginJars = new string[0];
        if (Directory.Exists(str4))
        {
            FileUtil.CopyDirectoryRecursive(str4, target, true);
            pluginJars = Directory.GetFiles(target, "*.jar", SearchOption.AllDirectories);
        }
        this.CreateDotClasspath(pluginJars);
        this.CreateDotProject();
        this.CreateDotSettings();
        string activityBaseName = this.ForgeActivityName();
        this.mManifestXml = this.ReadManifest();
        this.CopyJavaFiles(activityBaseName);
        this.WritePropertiesFile("default.properties");
        this.WritePropertiesFile("project.properties");
        this.mManifestXml.Save(Path.Combine(this.mProjectPath, "AndroidManifest.xml"));
    }

    private static XmlElement CreateBuildCommand(XmlDocument doc, string name, string arguments)
    {
        XmlElement element = doc.CreateElement("buildCommand");
        element.AppendChild(CreateTextNode(doc, "name", name));
        element.AppendChild(CreateTextNode(doc, "arguments", arguments));
        return element;
    }

    private static XmlElement CreateClasspathEntry(XmlDocument doc, string kind, string path)
    {
        XmlElement element = doc.CreateElement("classpathentry");
        XmlAttribute node = doc.CreateAttribute("kind");
        node.Value = kind;
        element.Attributes.Append(node);
        XmlAttribute attribute2 = doc.CreateAttribute("path");
        attribute2.Value = path;
        element.Attributes.Append(attribute2);
        if (kind == "lib")
        {
            XmlAttribute attribute3 = doc.CreateAttribute("exported");
            attribute3.Value = "true";
            element.Attributes.Append(attribute3);
        }
        return element;
    }

    private void CreateDotClasspath(string[] pluginJars)
    {
        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", string.Empty));
        XmlElement newChild = doc.CreateElement("classpath");
        newChild.AppendChild(CreateClasspathEntry(doc, "src", "src"));
        newChild.AppendChild(CreateClasspathEntry(doc, "src", "gen"));
        newChild.AppendChild(CreateClasspathEntry(doc, "con", "com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"));
        newChild.AppendChild(CreateClasspathEntry(doc, "lib", "classes.jar"));
        newChild.AppendChild(CreateClasspathEntry(doc, "output", "bin"));
        foreach (string str in pluginJars)
        {
            string path = FileUtil.RemovePathPrefix(str, this.mProjectPath);
            XmlElement element2 = CreateClasspathEntry(doc, "lib", path);
            newChild.AppendChild(element2);
        }
        doc.AppendChild(newChild);
        string filename = Path.Combine(this.mProjectPath, ".classpath");
        doc.Save(filename);
    }

    private void CreateDotProject()
    {
        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", string.Empty));
        XmlElement newChild = doc.CreateElement("projectDescription");
        newChild.AppendChild(CreateTextNode(doc, "name", this.mProductName));
        newChild.AppendChild(CreateTextNode(doc, "comment", string.Empty));
        newChild.AppendChild(CreateTextNode(doc, "projects", string.Empty));
        XmlElement element2 = doc.CreateElement("buildSpec");
        element2.AppendChild(CreateBuildCommand(doc, "com.android.ide.eclipse.adt.ResourceManagerBuilder", string.Empty));
        element2.AppendChild(CreateBuildCommand(doc, "com.android.ide.eclipse.adt.PreCompilerBuilder", string.Empty));
        element2.AppendChild(CreateBuildCommand(doc, "org.eclipse.jdt.core.javabuilder", string.Empty));
        element2.AppendChild(CreateBuildCommand(doc, "com.android.ide.eclipse.adt.ApkBuilder", string.Empty));
        newChild.AppendChild(element2);
        XmlElement element3 = doc.CreateElement("natures");
        element3.AppendChild(CreateTextNode(doc, "nature", "com.android.ide.eclipse.adt.AndroidNature"));
        element3.AppendChild(CreateTextNode(doc, "nature", "org.eclipse.jdt.core.javanature"));
        newChild.AppendChild(element3);
        doc.AppendChild(newChild);
        string filename = Path.Combine(this.mProjectPath, ".project");
        doc.Save(filename);
    }

    private void CreateDotSettings()
    {
        string path = Path.Combine(this.mProjectPath, ".settings");
        Directory.CreateDirectory(path);
        string contents = "eclipse.preferences.version=1\norg.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5\norg.eclipse.jdt.core.compiler.compliance=1.5\norg.eclipse.jdt.core.compiler.source=1.5\n";
        File.WriteAllText(Path.Combine(path, "org.eclipse.jdt.core.prefs"), contents);
    }

    private static XmlElement CreateTextNode(XmlDocument doc, string tag, string str)
    {
        XmlElement element = doc.CreateElement(tag);
        XmlText newChild = doc.CreateTextNode(str);
        element.AppendChild(newChild);
        return element;
    }

    private string ForgeActivityName()
    {
        string mProductName = this.mProductName;
        int startIndex = 0;
        while (startIndex < mProductName.Length)
        {
            char c = mProductName[startIndex];
            if (!char.IsLetterOrDigit(c) || (!char.IsLetter(c) && (startIndex == 0)))
            {
                mProductName = mProductName.Remove(startIndex, 1);
            }
            else
            {
                startIndex++;
            }
        }
        return mProductName;
    }

    private void PatchActivityInManifest(string activityName, string unityActivityName)
    {
        IEnumerator enumerator = this.mManifestXml.GetElementsByTagName("activity").GetEnumerator();
        try
        {
            while (enumerator.MoveNext())
            {
                XmlElement current = (XmlElement) enumerator.Current;
                if (current.Attributes["android:name"].Value.EndsWith(unityActivityName))
                {
                    current.Attributes["android:name"].Value = this.mPackageName + "." + activityName;
                }
            }
        }
        finally
        {
            IDisposable disposable = enumerator as IDisposable;
            if (disposable == null)
            {
            }
            disposable.Dispose();
        }
    }

    private XmlDocument ReadManifest()
    {
        string url = Path.Combine(this.mStagingArea, "AndroidManifest.xml");
        XmlDocument document = new XmlDocument();
        XmlTextReader reader = new XmlTextReader(url);
        reader.Read();
        document.Load(reader);
        reader.Close();
        return document;
    }

    private void WritePropertiesFile(string file)
    {
        File.WriteAllText(Path.Combine(this.mProjectPath, file), this.mTargetApi);
    }
}

